package com.ygq.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * ControllerExceptionHandler
 *
 * @author Yin Guiqing
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 异常处理
     *
     * @param request 请求
     * @param e       异常
     * @return 错误页面的 ModelAndView
     * @throws Exception 如果有确切状态码如 404、500 等，抛出交给 Spring Boot 处理，会自动到相应页面
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        logger.error("请求路径 : {}, 异常信息 : {}",
                request.getRequestURI(), e.getMessage());

        // 如果有确切状态码如 404、500 等，抛出交给 Spring Boot 处理，会自动到相应页面
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURI());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}
